package com.lantosec.hmrp.core.mvc;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author 杨成宇
 * @version 1.0
 */
public abstract class BaseServiceCache<R extends BaseRepository<T, ID>, T, ID> extends BaseService<R, T, ID> {
    /**
     * 单条件根据主键查询，未查找到会抛出异常
     *
     * @param key id
     * @return domain
     */
    @Transactional(readOnly = true)
    @Cacheable(key = "#key", unless = "#result != null")
    public T getByKey(ID key) {
        return repository.getOne(key);
    }

    /**
     * 单条件根据主键查询，未查找到不会抛出异常
     *
     * @param id id
     * @return Optional
     */
    @Transactional(readOnly = true)
    @Cacheable(key = "#id", unless = "#result != null")
    public T getById(ID id) {
        Optional<T> optional = repository.findById(id);
        return optional.isPresent() ? optional.get() : null;
    }


    /**
     * 根据id删除
     *
     * @param key id
     */
    @Transactional
    @CacheEvict(key = "#key")
    public void deleteById(ID key) {
        repository.deleteById(key);
    }


    /**
     * 批量删除所有
     */
    @Transactional
    @CacheEvict(allEntries=true)
    public void deleteAllInBatch() {
        repository.deleteAllInBatch();
    }

    /**
     * 更新
     *
     * @param entity 更新参数
     * @param id     需要根据id过滤null值
     * @return 更新的结果
     */
    @Transactional
    @CachePut(key = "#id")
    public T update(T entity, ID id) {
        /*
        T object = repository.getOne(id);
        T entity = getEntity();
        BeanUtils.copyProperties(vo, entity);
        //将object复制给entity 忽略的属性是有值的属性（将object复制到entity属性为null）
        BeanUtils.copyProperties(object, entity, getNoNullProperties(entity));
        repository.save(entity);
        return entity;
        */
        return super.update(entity,id);
    }
}
